<template>
  <PageWrapper title="">
    <XGrid ref="xGrid"
      :columns="columns"
      :show-overflow="true"
      :line="true"
      :stripe="false"
      :checkStrictly="true"
      is-tree
      @create="drawer.data.show = true"
      @edit="handleEdit"
      @copy="handleCopy">
      <template #topLeft2>
        <a class="btn" @click="edit" :class="{disabled:editDisabled}">编辑</a>
        <Divider type="vertical"/>
        <a @click="setAllTreeExpand">展开/收起</a>
      </template>
    </XGrid>
    <Drawer :show="drawer.data.show" :is-update="drawer.data.isUpdate"
        :row="drawer.data.row"
        @on-success="onSuccess"
        @on-drawer-close="onDrawerClose"/>
  </PageWrapper>
</template>
<script lang="ts" name="Menu" setup>
import {ref, reactive, toRaw, watchPostEffect} from 'vue';
import {PageWrapper} from '/@/components/Page';
import {XGrid} from '/@/components/XGrid';
import {columns} from './data';
import Drawer from './Drawer.vue';
import {create,} from '/@/api/admin/menu';
import {Divider} from 'ant-design-vue';

const xGrid = ref();

const drawer = reactive({data: {
  show: false,
  isUpdate: false,
  row: null,
}})

const handleEdit = (row_:any) => {
  drawer.data.show = true
  drawer.data.isUpdate = true
  drawer.data.row = row_
}

const handleCopy = (row:any) => {
    let data = toRaw(row)
    data.id = null
    data.path = ''+new Date().getTime()
    data.name = ''+new Date().getTime()
    data.metaId = null
    data!.meta!.id = null
    create(data).then(() => {
      onSuccess()
    })
}

const onDrawerClose = () => {
  Object.assign(drawer, {data: {}})
}

const onSuccess = () => {
  xGrid.value.reload()
}

const allExpand = ref(true)
const setAllTreeExpand = () => {
  allExpand.value = !allExpand.value
  xGrid.value.setAllTreeExpand(allExpand.value)
}

const outEdit = reactive({data: {
  disabled: true,
  row: null,
}})
const editDisabled = ref(true)
const edit = () => {
  handleEdit(outEdit.data.row)
}

watchPostEffect(() => {
  let list = xGrid.value.getCheckedList()
  editDisabled.value = !(list.length === 1)
  if (!editDisabled.value) {
    outEdit.data.row = toRaw(list[0])
  } else {
    outEdit.data.row = null
  }
})

</script>
